<template>
    <div class="app-container">
        <el-row :gutter="15">
            <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="130px">
                <el-col :span="18">
                    <el-form-item label="货品名称" prop="goodsName">
                        <el-input v-model="formData.goodsName" placeholder="请输入货品名称" show-word-limit clearable
                                  :style="{width: '100%'}"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="18">
                    <el-form-item label="货品大类" prop="goodsCategory">
                        <el-radio-group v-model="formData.goodsCategory" @change="changeGoodsType" size="medium">
                            <el-radio v-for="(item, index) in goodsCategoryOptions" :key="index" :label="item.dictValue">
                                {{item.dictLabel}}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="18">
                    <el-form-item label="货品小类" prop="goodsType">
                        <el-select v-model="formData.goodsType" size="medium">
                            <el-option
                                    v-for="item in goodsTypeOptions"
                                    :key="item.dictValue"
                                    :label="item.dictLabel"
                                    :value="item.dictValue"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="18">
                    <el-form-item label="货品估价" prop="goodsPrice">
                        <el-input v-model="formData.goodsPrice" placeholder="请输入货品的市场估价" show-word-limit clearable
                                  :style="{width: '100%'}">
                            <template slot="append">元</template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="18">
                    <el-form-item label="计量单位" prop="goodsMeasurementUnit">
                        <el-input v-model="formData.goodsMeasurementUnit" placeholder="请输入货品的计量单位" show-word-limit clearable
                                  :style="{width: '100%'}"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="18">
                    <el-form-item label="预警阀值" prop="waringNumber">
                        <el-input-number v-model="formData.waringNumber" controls-position="right" :min="1"/>
                    </el-form-item>
                </el-col>
                <el-col :span="18">
                    <el-form-item label="条形码标识" prop="goodsBarCode">
                        <el-input v-model="formData.goodsBarCode" placeholder="请输入条形码标识" show-word-limit clearable
                                  :style="{width: '100%'}"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="18">
                    <el-form-item label="二维码标识" prop="goodsQrCode">
                        <el-input v-model="formData.goodsQrCode" placeholder="请输入二维码标识" show-word-limit clearable
                                  :style="{width: '100%'}"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="18">
                    <el-form-item label="货品描述" prop="goodsDes">
                        <el-input v-model="formData.goodsDes" type="textarea" placeholder="请输入货品描述信息"
                                  show-word-limit
                                  :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="18">
                    <el-form-item v-for="(item,index) in formData.goodsAttrList"
                                  :label="'商品属性 ' + (index+1)"
                                  :key="index"
                                  :prop="'goodsAttrList.' + index + '.attrName'"
                                  :rules="{
                                    required: true, message: '货品属性不能为空', trigger: 'blur'
                                    }"
                    >
                        <el-input v-model="item.attrName" class="inputWidth" placeholder="请输入货品属性名" clearable></el-input>
                        <el-input v-model="item.attrValue" class="inputWidth" placeholder="请输入货品属性值描述" clearable></el-input>
                        <el-button v-if="index == formData.goodsAttrList.length-1" @click="addItem" type="success" icon="el-icon-plus" circle  size="mini"></el-button>
                        <el-button @click="delItem(index)" type="danger" icon="el-icon-delete" circle  size="mini"></el-button>
                    </el-form-item>
                </el-col>
                <el-col :span="18">
                    <el-form-item label="货品图片">
                        <el-upload ref="imgaeRef"
                                   :file-list="imageFileList"
                                   :auto-upload="false"
                                   action=""
                                   :limit="5"
                                   :on-exceed="OnImageExceed"
                                   :before-upload="imageBeforeUpload"
                                   list-type="picture-card"
                                   accept="image/*" >
                            <i class="el-icon-plus"></i>
                            <div slot="tip" class="el-upload__tip">只能上传不超过 5MB 的image/*文件，最多上传5张图片</div>
                        </el-upload>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item size="large">
                        <el-button type="primary" @click="submitForm" :loading="loginLoading">提交</el-button>
                        <el-button @click="resetForm">重置</el-button>
                    </el-form-item>
                </el-col>
            </el-form>
        </el-row>
    </div>
</template>
<script>
    import {addGoods} from "@/api/goods/goods.js";

    export default {
        components: {},
        props: [],
        data() {
            return {
                formData: {
                    goodsName: '',
                    goodsCategory: '',
                    goodsType: '',
                    goodsPrice: '',
                    goodsMeasurementUnit: '',
                    waringNumber: 100,
                    goodsBarCode: '',
                    goodsQrCode: '',
                    goodsDes: '',
                    goodsAttrList: [
                        {attrName: '',attrValue: ''}
                    ]
                },
                realFormData: new FormData(),
                rules: {
                    goodsName: [{
                        required: true,
                        message: '请输入货品名称',
                        trigger: 'blur'
                    }],
                    goodsPrice: [{
                        required: true,
                        message: '请输入货品市场估价',
                        trigger: 'blur'
                    }],
                    goodsMeasurementUnit: [{
                        required: true,
                        message: '请输入计量单位',
                        trigger: 'blur'
                    }],
                    waringNumber: [{
                        required: true,
                        message: '请输入库存不足预警阀值',
                        trigger: 'change'
                    }]
                },
                goodsCategoryOptions: [],
                goodsTypeOptions: [],
                imageFileList: [],
                loginLoading: false
            }
        },
        computed: {},
        watch: {},
        created() {
            let app = this;
            app.getDicts("goods_info_goods_category").then(response => {
                app.goodsCategoryOptions = response.data;
                var dataList = response.data;
                if(dataList != null && dataList.length>0){
                    app.formData.goodsCategory = dataList[0].dictValue;
                    app.getDicts("goods_category_" +  dataList[0].dictValue).then(response1 => {
                        app.goodsTypeOptions = response1.data;
                        app.formData.goodsType = response1.data[0].dictValue;
                    });
                }
            });
        },
        mounted() {
        },
        methods: {
            changeGoodsType(){
                let app = this;
                app.getDicts("goods_category_" +  this.formData.goodsCategory).then(response1 => {
                    app.goodsTypeOptions = response1.data;
                    app.formData.goodsType = response1.data[0].dictValue;
                });
            },
            submitForm() {
                this.$refs['elForm'].validate(valid => {
                    if (valid) {
                        let app = this;
                        app.loginLoading = true;
                        setTimeout(function () {
                            //上传函数，如果把提交函数用在http-request钩子中，
                            // fileList多长就执行请求多少次接口，依旧是无法做到只请求一次上传多文件
                            //  用FormData存放上传文件
                            app.realFormData.append("goodsName",app.formData.goodsName);
                            app.realFormData.append("goodsCategory",app.formData.goodsCategory);
                            app.realFormData.append("goodsType",app.formData.goodsType);
                            app.realFormData.append("goodsPrice",app.formData.goodsPrice);
                            app.realFormData.append("goodsMeasurementUnit",app.formData.goodsMeasurementUnit);
                            app.realFormData.append("waringNumber",app.formData.waringNumber);
                            app.realFormData.append("goodsBarCode",app.formData.goodsBarCode);
                            app.realFormData.append("goodsQrCode",app.formData.goodsQrCode);
                            app.realFormData.append("goodsDes",app.formData.goodsDes);
                            app.realFormData.append("goodsAttrListJson",JSON.stringify(app.formData.goodsAttrList));
                            //进行elementUi上传组件的提交触发
                            app.$refs['imgaeRef'].submit();

                            addGoods(app.realFormData).then(response => {
                                if (response.code === 200) {
                                    app.msgSuccess("新增货品成功！");
                                } else {
                                    app.msgError(response.msg);
                                }
                            });
                            app.realFormData = new FormData();
                        },1000);
                        app.loginLoading = false;
                    }
                })
            },
            resetForm() {
                this.$refs['elForm'].resetFields()
            },
            imageBeforeUpload(file) {
                let isRightSize = file.size / 1024 / 1024 < 5
                if (!isRightSize) {
                    this.$message.error('文件大小超过 5MB')
                }
                let isAccept = new RegExp('image/*').test(file.type)
                if (!isAccept) {
                    this.$message.error('应该选择image/*类型的文件')
                }

                if (isRightSize && isAccept) {
                    this.realFormData.append('imageFile', file);
                    return false;
                } else {
                    return false;
                }
            },
            OnImageExceed(file, fileList) {
                this.$message.error(`只能上传5张图片!`);
            },
            addItem(){
                //添加一个空的数组元素
                this.formData.goodsAttrList.push({attrName: '',attrValue: ''});
            },
            delItem(index){
                //移除指定索引的数组元素
                this.formData.goodsAttrList.splice(index,1);
            }
        }
    }

</script>
<style>
    .el-upload__tip {
        line-height: 1.2;
    }

    .inputWidth{
        width: 40%;
        margin-right: 15px;
    }
</style>

